<template>
    <div>
        <div class="cropper-content">
            <div class="cropper">
                <vueCropper
                    ref="cropper"
                    :img="option.img"
                    :outputSize="option.size"
                    :outputType="option.outputType"
                    :info="true"
                    :full="option.full"
                    :canMove="option.canMove"
                    :canMoveBox="option.canMoveBox"
                    :original="option.original"
                    :autoCrop="option.autoCrop"
                    :autoCropWidth="option.autoCropWidth"
                    :autoCropHeight="option.autoCropHeight"
                    :fixedBox="option.fixedBox"
                    :centerBox="option.centerBox"
                    @realTime="realTime"
                    @imgLoad="imgLoadd"
                ></vueCropper>
            </div>
            <div
                class="show-preview"
                :style="{
                    width: previews.div + 'px',
                    height: previews.div + 'px',
                    overflow: 'hidden',
                    margin: '5px'
                 }"
            >
                <div :style="previews.div" class="preview">
                    <img :src="previews.url" :style="previews.img" />
                </div>
            </div>
        </div>

        <div class="footer-btn">
            <div class="scope-btn">
                <label class="btn" for="uploads">选择图片</label>
                <input
                    type="file"
                    id="uploads"
                    style="position:absolute; clip:rect(0 0 0 0);"
                    accept="image/png, image/jpeg, image/gif, image/jpg"
                    @change="uploadImg($event, 1)"
                />
                <Button @click="changeScale(1)" icon="md-add"></Button>
                <Button @click="changeScale(-1)" icon="md-remove"></Button>
                <Button @click="rotateLeft"
                    ><span style="font-size: 14px;">↺</span></Button
                >
                <Button @click="rotateRight"
                    ><span style="font-size: 14px;">↻</span></Button
                >
            </div>
            <div class="upload-btn">
                <Button
                    type="primary"
                    style="margin-left: 46px;"
                    @click="down()"
                    >上传头像</Button
                >
            </div>
        </div>
    </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
export default {
    data() {
        return {
            crap: false,
            previews: {},
            option: {
                img: '',
                size: 1,
                full: false, // 输出原图比例截图 props名full
                outputType: 'png',
                canMove: true,
                original: false,
                canMoveBox: true,
                autoCrop: true,
                autoCropWidth: 200,
                autoCropHeight: 200,
                fixedBox: true,
                centerBox: true,
            },
            imgLoad:'',
            fileName:'',//图片名字
            updateUser:''
        }
    },
    components: { VueCropper },
    methods: {
        changeScale(num) {
            num = num || 1
            this.$refs.cropper.changeScale(num)
        },
        rotateLeft() {
            this.$refs.cropper.rotateLeft()
        },
        rotateRight() {
            this.$refs.cropper.rotateRight()
        },
        // 实时预览函数
        realTime(data) {
            this.previews = data
        },
        down() {
            //在this.$refs.cropper.getCropData(data)方法中的参数data，就是剪接图片后的base64格式
            this.$refs.cropper.getCropData(data => {
                //将图片的名字作为参数，传给后端
                let fileName=this.fileName;
                //将userId作为参数，传给后端
                let userId=JSON.parse(localStorage.getItem("user")).userId;
                    this.$axios.post('/api/user/uploadImg',
                  {
                      data:data,
                      userId:userId,
                      fileName:fileName
                  }
            ).then(res => {
              //更新本地信息
              let user = JSON.stringify(res.data);
              localStorage.setItem("user", user);
              // 通知父组件关闭头像裁剪弹框,并将更新的user返回给父组件进行页面的更新
              this.updateUser=JSON.parse(localStorage.getItem("user"));
              this.$emit('hide_mkhead_modal',this.updateUser);
              this.$Message.success('头像上传成功');
              this.$refs.cropper.clearCrop();
                    })
            })

        },
		/**
		 * 上传头像到服务器的回调
		 */
        callback_avatar(ret) {
            if (ret.code == 200) {
                // 保存用户信息
                this.user.headpic = ret.data.headpic;
                this.set_user_info(this.user);
                // 通知父组件关闭头像裁剪弹框
                this.$emit('hide_mkhead_modal');
                this.$Message.success(ret.msg);
                this.$refs.cropper.clearCrop();
            } else {
                this.$Message.error(ret.msg);
            }
        },

        //选择本地图片
        uploadImg(e, num) {
            //获取打开的本地图片
            var file = e.target.files[0]
            //获取图片的名字赋值给this.fileName，并进行验证是否符合指定的格式
            this.fileName = file.name;
            if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                this.$Message.error('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                return false
            }
            //创建FileReader进行图片的读取
            var reader = new FileReader()
            reader.onload = e => {
                let data
                if (typeof e.target.result === 'object') {
                    // 把Array Buffer转化为blob 如果是base64不需要
                    data = window.URL.createObjectURL(new Blob([e.target.result]))
                } else {
                    data = e.target.result
                }
                if (num === 1) {
                    this.option.img = data
                } else if (num === 2) {
                    this.example2.img = data
                }
            }
            // 转化为base64，即将
            reader.readAsDataURL(file)
            // 转化为blob
           // reader.readAsArrayBuffer(file)
        },
        //判断实时图片是否为sucess(还没看懂)
        imgLoadd(msg) {
            this.imgLoad=msg
        }
    }
}
</script>
<style lang="less">
    .cropper-content {
        display: flex;
        display: -webkit-flex;
        justify-content: flex-end;
        -webkit-justify-content: flex-end;
        .cropper {
            width: 350px;
            height: 300px;
        }
        .show-preview {
            flex: 1;
            -webkit-flex: 1;
            display: flex;
            display: -webkit-flex;
            justify-content: center;
            -webkit-justify-content: center;
            .preview {
                overflow: hidden;
                border-radius: 50%;
                border: 1px solid #cccccc;
                background: #cccccc;
                margin-left: 40px;
            }
        }
    }
    .footer-btn {
        margin-top: 30px;
        display: flex;
        display: -webkit-flex;
        justify-content: flex-end;
        -webkit-justify-content: flex-end;
        .scope-btn {
            width: 350px;
            display: flex;
            display: -webkit-flex;
            justify-content: space-between;
            -webkit-justify-content: space-between;
        }
        .upload-btn {
            flex: 1;
            -webkit-flex: 1;
            display: flex;
            display: -webkit-flex;
            justify-content: center;
            -webkit-justify-content: center;
        }
        .btn {
            outline: none;
            display: inline-block;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            -webkit-appearance: none;
            text-align: center;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            outline: 0;
            margin: 0;
            -webkit-transition: 0.1s;
            transition: 0.1s;
            font-weight: 500;
            padding: 10px 15px;
            font-size: 12px;
            border-radius: 3px;
            color: #fff;
            background-color: #67c23a;
            border-color: #67c23a;
        }
    }
</style>